package com.ai.wx.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ai.core.constant.GlobalConstant;
import com.ai.core.pagemode.Grid;
import com.ai.core.pagemode.Json;
import com.ai.core.pagemode.PageFilter;
import com.ai.core.util.Configure;
import com.ai.wx.entity.AgentBrokerageDraw;
import com.ai.wx.entity.AgentUser;
import com.ai.wx.entity.PAgentBrokerageDraw;
import com.ai.wx.exception.FlowMarketException;
import com.ai.wx.service.AdminService;
import com.ai.wx.service.AgentService; 
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

@Controller
@RequestMapping("/ht")
public class AdminViewController {

	@Autowired
	private AgentService agentService;
	@Autowired
	private AdminService adminService;
	
	@ModelAttribute  
    public void checkPri() throws FlowMarketException {   
    }  
	
	@RequestMapping("/login")
	public String login(){ 
		return "/admin/login";
	}
	
	@RequestMapping("/doLogin")
	@ResponseBody
	public Json doLogin(String username, String password,String code,HttpServletRequest request) throws IOException {
		Json j = new Json();
		try {
			if (request.getSession().getAttribute("loginCode") != null) {
				String loginCode = (String) request.getSession().getAttribute("loginCode");
				if (StringUtils.equalsIgnoreCase(loginCode, code)) {
					j  = adminService.doLogin(username,password);  
					request.getSession().setAttribute(GlobalConstant.SESSION_USER, j.getObj());
				}else{ 
					j.setMsg("验证码输入错误");
				}
			}else{ 
				j.setMsg("获取验证码失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());

		}
		return j;
	}
	
	

	@RequestMapping("/loginCode")
	public void loginCode(HttpServletRequest request, HttpServletResponse response) throws IOException {

		try {
			response.setHeader("Pragma", "No-cache");
			response.setHeader("Cache-Control", "no-cache");
			response.setDateHeader("Expires", 0);
			int width = 100, height = 34;
			BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
			OutputStream os = response.getOutputStream();
			Graphics g = image.getGraphics();
			Random random = new Random();
			g.setColor(getRandColor(200, 250));
			g.fillRect(0, 0, width, height);
			g.setFont(new Font("Arial", Font.PLAIN, 28));
			g.setColor(getRandColor(160, 200));
			for (int i = 0; i < 155; i++) {
				int x = random.nextInt(width);
				int y = random.nextInt(height);
				int xl = random.nextInt(12);
				int yl = random.nextInt(12);
				g.drawLine(x, y, x + xl, y + yl);
			}
			String sRand = "";
			for (int j = 0; j < 4; j++) {
				String rand = RandomStringUtils.randomAlphanumeric(1);
				
				sRand += rand;
				g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
				g.drawString(rand, 20 * j + 10, 24);
			}
			// RandomStringUtils.randomNumeric(4);
			request.getSession().setAttribute("loginCode", sRand);
			g.dispose();
			ImageIO.write(image, "JPEG", os);
			os.flush();
			os.close();
			os = null;
			response.flushBuffer();
		} catch (IllegalStateException e) {
			e.printStackTrace();
		}

	}
	
	public Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}
	
	
	@RequestMapping("/checkLoginCode")
	@ResponseBody
	public boolean checkLoginCode(String code, HttpServletRequest request) throws IOException {
		if (request.getSession().getAttribute("loginCode") != null) {
			String regRandomCode = (String) request.getSession().getAttribute("loginCode");
			if (StringUtils.equalsIgnoreCase(regRandomCode, code)) {
				return true;
			}
		}
		return false;
	}

	
	
	@RequestMapping("/agentUserApprove")
	public String agentUserApprove(){ 
		return "/admin/agentUserApprove";
	}
	
	@RequestMapping("/getAgentUserList")
	@ResponseBody
	public Grid getAgentUserList(AgentUser agentUser,PageFilter pf) {
		Grid grid = new Grid();
		List<AgentUser> list = adminService.getAgentUserList(agentUser, pf);
		grid.setRows(list);

		Long total = adminService.countAgentUserList(agentUser);
		grid.setTotal(total);
  		return grid;
	}
	
	@RequestMapping("/approveAgent")
	@ResponseBody
	public Json approveAgent(AgentUser agentUser) throws IOException {
		Json j = new Json();
		try {
			j = adminService.saveAgentUser(agentUser);
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());

		}
		return j;
	}
	
	
	@RequestMapping("/brokerageDrawApprove")
	public String brokerageDrawApprove(){ 
		return "/admin/brokerageDrawApprove";
	}
	
	@RequestMapping("/getBrokerageDrawList")
	@ResponseBody
	public Grid getBrokerageDrawList(PAgentBrokerageDraw pAgentBrokerageDraw,PageFilter pf) {
		Grid grid = new Grid();
		List<PAgentBrokerageDraw> list = adminService.getBrokerageDrawList(pAgentBrokerageDraw, pf);
		grid.setRows(list);

		Long total = adminService.countBrokerageDrawList(pAgentBrokerageDraw);
		grid.setTotal(total);
  		return grid;
	}
	
	
	
	@RequestMapping("/approveDrawBrokerage")
	@ResponseBody
	public Json approveDrawBrokerage(AgentBrokerageDraw draw) throws IOException {
		Json j = new Json();
		try {
			j = adminService.approveDrawBrokerage(draw); 
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());

		}
		return j;
	}
	
	@RequestMapping("/refuseDrawBrokerage")
	@ResponseBody
	public Json refuseDrawBrokerage(AgentBrokerageDraw draw) throws IOException {
		Json j = new Json();
		try {
			j = adminService.refuseDrawBrokerage(draw); 
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());

		}
		return j;
	}
	
	
	@RequestMapping("/adminLogin")
	@ResponseBody
	public Json adminLogin(String userName,String password,String code) throws IOException {
		Json j = new Json();
		try { 
		} catch (Exception e) {
			e.printStackTrace();
			j.setMsg(e.getMessage());

		}
		return j;
	}
	
	

	@RequestMapping("/image/{fileName}.{fileExt}")
	public void image(@PathVariable("fileName") String fileName, @PathVariable("fileExt") String fileExt, HttpServletRequest request, HttpServletResponse response) throws IOException {
		String imagePath = Configure.getString("IMAGE_DIR") + File.separator + fileName + "." + fileExt;

		showPic(request, response, imagePath);
	}

	private static final String GIF = "image/gif;charset=UTF-8";// 设定输出的类型

	private static final String JPG = "image/jpeg;charset=UTF-8";

	private static final String PNG = "image/png;charset=UTF-8";
	
	private void showPic(HttpServletRequest request, HttpServletResponse response, String imagePath) throws IOException, FileNotFoundException {
		response.reset();

		OutputStream output = response.getOutputStream();// 得到输出流
		if (imagePath.toLowerCase().endsWith(".jpg") || imagePath.toLowerCase().endsWith(".jpeg"))// 使用编码处理文件流的情况：
		{
			response.setContentType(JPG);// 设定输出的类型
			// 得到图片的真实路径

			// 得到图片的文件流
			InputStream imageIn = new FileInputStream(new File(imagePath));
			// 得到输入的编码器，将文件流进行jpg格式编码
			JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(imageIn);
			// 得到编码后的图片对象
			BufferedImage image = decoder.decodeAsBufferedImage();
			// 得到输出的编码器
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(output);
			encoder.encode(image);// 对图片进行输出编码
			imageIn.close();// 关闭文件流
		}
		if (imagePath.toLowerCase().endsWith(".gif"))// 不使用编码处理文件流的情况：
		{
			response.setContentType(GIF);
			InputStream imageIn = new FileInputStream(new File(imagePath));
			BufferedInputStream bis = new BufferedInputStream(imageIn);// 输入缓冲流
			BufferedOutputStream bos = new BufferedOutputStream(output);// 输出缓冲流
			byte data[] = new byte[4096];// 缓冲字节数
			int size = 0;
			size = bis.read(data);
			while (size != -1) {
				bos.write(data, 0, size);
				size = bis.read(data);
			}
			bis.close();
			bos.flush();// 清空输出缓冲流
			bos.close();
		}
		if (imagePath.toLowerCase().endsWith(".png"))// 不使用编码处理文件流的情况：
		{
			response.setContentType(PNG);
			InputStream imageIn = new FileInputStream(new File(imagePath));
			BufferedInputStream bis = new BufferedInputStream(imageIn);// 输入缓冲流
			BufferedOutputStream bos = new BufferedOutputStream(output);// 输出缓冲流
			byte data[] = new byte[4096];// 缓冲字节数
			int size = 0;
			size = bis.read(data);
			while (size != -1) {
				bos.write(data, 0, size);
				size = bis.read(data);
			}
			bis.close();
			bos.flush();// 清空输出缓冲流
			bos.close();
		}
		output.close();
	}
}
